package com.dongdongshop.service.impl.mail_quartz;

import com.dongdongshop.job.MailJob;
import com.dongdongshop.service.mail_quartz.MailQuartzService;
import org.apache.catalina.User;
import org.apache.commons.lang3.RandomStringUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
@Service
@com.alibaba.dubbo.config.annotation.Service
public class MailQuartzServiceImpl implements MailQuartzService {
    @Autowired
    private Scheduler scheduler;
    public void mailQuartz() {
        String tiggeer = RandomStringUtils.randomNumeric(4);
        // 根据name和group获取当前trigger身份
        TriggerKey triggerKey = TriggerKey.triggerKey(tiggeer, "gg");
        CronTrigger oldTrigger = null;

        // 获取触发器的信息
        try {
            oldTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        if (oldTrigger == null) {
            // 将job添加到JobDetail中
            JobDetail jobDetail = JobBuilder.newJob(MailJob.class)
                    .usingJobData("name", "发送邮件")
                    .withIdentity(tiggeer+"1", "gg")
                    .build();
          /*  LocalDateTime now = LocalDateTime.now();
            LocalDateTime localDateTime = now.plusDays(15);
            int monthValue = localDateTime.getMonthValue();
            int dayOfMonth = localDateTime.getDayOfMonth();
            int year = localDateTime.getYear();*/
            // 创建触发器
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .usingJobData(tiggeer, "缓存更新触发器")
                    .withIdentity(tiggeer, "gg")
                    .withSchedule(CronScheduleBuilder.cronSchedule("0 30 12 * * ?"))
                    .build();

            // 执行任务
            try {
                scheduler.scheduleJob(jobDetail, trigger);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }

        } else {
            throw new RuntimeException("用户已存在");
        }


    }
}

